import React, { Component, PureComponent, useRef, useState } from 'react';
import { StyleSheet, Text, View, Button, DeviceEventEmitter, TouchableOpacity, SafeAreaView, Dimensions, Animated,
  ScrollView, ImageBackground, useWindowDimensions, Easing
 } from 'react-native';
import styles from './styles';

const TopTabBar = ({ data, style }) => {
  const tabs = data && data.length;

  const screenWidth = Dimensions.get('screen').width;
  const marginHorizontal = 20;
  const tabDividerSpace = 10;
  const indicatorWidth = (screenWidth - marginHorizontal * 4 - tabDividerSpace * (tabs - 1)) / tabs;

  const indicatorLeft = useRef(new Animated.Value(0)).current;
  const [activeIndex, setActiveIndex] = useState(0);
  const [contentScrollView, setContentScrollView] = useState(null)

  const onPressBar = (index) => {
    setActiveIndex(index);
    // console.log(contentScrollView);
    // contentScrollView.scrollTo({x: index});
    const newLeft = (indicatorWidth + tabDividerSpace) * index;
    Animated.timing(
      indicatorLeft,
      {
        toValue: newLeft,
        duration: 500,
        easing: Easing.elastic(1),
        useNativeDriver: false,
      }
    ).start(); 
  }

  const scrollX = useRef(new Animated.Value(0)).current;

  return (
    <>
      <View style={[styles.tabContainer, { marginHorizontal, paddingHorizontal: marginHorizontal }, style]}>
        <View style={styles.buttonsContainer}>
          {
            tabs && data.map((item, index) => {
              return (
                <TouchableOpacity
                  style={[styles.touchAble, { width: indicatorWidth }]}
                  onPress={() => { onPressBar(index) }}
                  key={item.key}
                >
                  <Text style={[styles.barTitle, { opacity: activeIndex === index ? 1 : 0.5 }]}>{item.key}</Text>
                </TouchableOpacity>
              )
            })
          }
        </View>
        <View style={{ width: '100%' }}>
          <Animated.View style={[
            styles.indicator,
            { width: indicatorWidth, },
            { left: indicatorLeft, }
          ]} />
        </View>
      </View>
      {/* <ScrollView
        horizontal={true}
        style={styles.scrollViewStyle}
        pagingEnabled
        showsHorizontalScrollIndicator={false}
        ref={(ref) => setContentScrollView(ref)}
        onScroll={Animated.event([
          {
            nativeEvent: {
              contentOffset: {
                x: scrollX
              }
            }
          }
        ])}
        scrollEventThrottle={1}
      >
        {
          tabs && data.map((item, index) => {
            return (
              item.content
            )
          })
        }
      </ScrollView> */}
      <View>
        {
          tabs && data.map((item, index) => {
            return activeIndex === index ? item.content : null;
          })
        }
      </View>
    </>
  );
}

export default TopTabBar;
